package com.example.demo.web.session;

import com.alibaba.fastjson.JSON;
import com.example.demo.bean.User;
import com.example.demo.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 1EnableRedisHttpSession 导入了RedisHttpSessionConfiguration 配置
 * 1.1 给容器中添加了一个组件，RedisIndexedSessionRepository 组件。
 * 1.2 SessionRepositoryFilter  -->filter过滤器
 */
@Slf4j
@RestController
@RequestMapping("/session")
public class SessionController {


    @RequestMapping("login")
    public String login(HttpServletRequest req, HttpServletResponse resp, HttpSession session,
                        User user) {
        //TODO 1 默认发的令牌，SESSION=*** ，作用域：当前域（解决子域共享）
        //TODO 2使用JSON的序列化存储数据到 Redis
        log.info("login user is {}", user);
        session.setAttribute(SysUtils.LOGIN_NAME, user);
        return String.format("%s|%s|", SysUtils.getDateSpan(), user.getUname());
    }

    @RequestMapping("show")
    public Object showLoginUser(HttpSession session) {
        Object attribute = session.getAttribute(SysUtils.LOGIN_NAME);
        log.info("获取的session user is {}", JSON.toJSONString(attribute));
        return attribute;
    }

    @RequestMapping("getsessionid")
    public String getSessionId(HttpSession session) {
        String sessionId = session.getId();
        return String.format("sessionId is =%s", sessionId);
    }
}
